import { query } from '../config/db.js';
import logger from '../config/logger.js';
import cache from '../config/redis.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { timestampToDateTime } from '../utils/tool.fun.js';




// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取秒杀Lua脚本
const seckillScript = fs.readFileSync(path.join(__dirname, '../utils/seckill.lua'), 'utf8');

/**
 * 获取所有社团报名记录
 */
const getClubRegistrations = async (req, res) => {
    try {
        // 尝试从缓存获取
        const cacheKey = 'club_registrations:all';
        const cachedRegistrations = await cache.get(cacheKey);

        if (cachedRegistrations) {
            logger.info('从缓存获取社团报名记录列表');
            // 检查cachedRegistrations是否已经是对象
            if (typeof cachedRegistrations === 'object') {
                return res.json({
                    registrations: cachedRegistrations
                });
            } else {
                // 尝试解析为JSON
                try {
                    return res.json({
                        registrations: JSON.parse(cachedRegistrations)
                    });
                } catch (jsonError) {
                    logger.error(`解析缓存的JSON失败: ${jsonError.message}`);
                }
            }
        }

        // 缓存未命中或解析失败，从数据库获取
        const result = await query('SELECT * FROM club_registrations');
        const registrations = result.rows;

        // 存入缓存，设置10分钟过期
        await cache.set(cacheKey, registrations, 600);
        logger.info('从数据库获取社团报名记录列表并缓存');

        res.json({
            registrations
        });
    } catch (error) {
        logger.error('获取社团报名记录列表错误:', error);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

/**
 * 根据ID获取社团报名记录
 */
const getClubRegistrationById = async (req, res) => {
    try {
        const { id } = req.params;
        const cacheKey = `club_registrations:${id}`;

        // 尝试从缓存获取
        const cachedRegistration = await cache.get(cacheKey);

        if (cachedRegistration) {
            logger.info(`从缓存获取社团报名记录ID: ${id}`);
            // 检查cachedRegistration是否已经是对象
            if (typeof cachedRegistration === 'object') {
                return res.json({
                    registration: cachedRegistration
                });
            } else {
                // 尝试解析为JSON
                try {
                    return res.json({
                        registration: JSON.parse(cachedRegistration)
                    });
                } catch (jsonError) {
                    logger.error(`解析缓存的JSON失败: ${jsonError.message}`);
                }
            }
        }

        // 缓存未命中或解析失败，从数据库获取
        const result = await query('SELECT * FROM club_registrations WHERE id = ?', [id]);

        if (result.rows.length === 0) {
            return res.status(404).json({
                message: '社团报名记录不存在'
            });
        }

        const registration = result.rows[0];

        // 存入缓存，设置10分钟过期
        await cache.set(cacheKey, registration, 600);
        logger.info(`从数据库获取社团报名记录ID: ${id}并缓存`);

        res.json({
            registration
        });
    } catch (error) {
        logger.error(`根据ID获取社团报名记录错误: ${error.message}`);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

// 从缓存中获取所有社团报名记录
const getClubRegistrationsFromCache = async (req, res) => {
    const keyValuePairs = await cache.getAll('club:student:', false);
    // console.log('所有缓存键值对:', keyValuePairs);
    return res.status(400).json({
        message: keyValuePairs
    });
};


/**
 * 社团秒杀报名
 */
const seckillClubRegistration = async (req, res) => {
    // console.log('seckillClubRegistration:社团秒杀报名', req.body);
    // console.log('时间：', timestampToYmdhm(Date.now()));
    // 从缓存中获取所有键值对
    // const keyValuePairs = await cache.getAll('club:student:',false);
    // // console.log('所有缓存键值对:', keyValuePairs);

    // return res.status(400).json({
    //     message: keyValuePairs
    // });
    try {
        // 从缓存中获取秒杀状态：进行中、未开始、已结束
        const seckillStatus = await getSeckillStatus();
        // console.log('seckillStatus', seckillStatus);
        // return res.status(400).json({
        //     message: seckillStatus
        // });
        if (seckillStatus === '未开始') {
            return res.status(400).json({
                message: '秒杀尚未开始'
            });
        }
        if (seckillStatus === '已结束') {
            return res.status(400).json({
                message: '秒杀已结束'
            });
        }

        // ======秒杀逻辑==========
        const { class_name, student_name, club_name } = req.body;

        // 验证必要字段
        if (!class_name || !student_name || !club_name) {
            return res.status(400).json({
                message: '班级名称、学生姓名和社团名称为必填项'
            });
        }

        // 从缓存中获取社团信息
        const club = await getClubInfo(club_name);
        console.log('club', club);
        const clubLimit = club.member_count;
        const clubLocation = club.location;

        // 设置Redis键
        const studentKey = `club:student:${class_name}:${student_name}:registration`;
        const clubCountKey = `club:${club_name}:count`;
        const clubLimitKey = `club:${club_name}:limit`;

        // 设置社团人数上限
        await cache.set(clubLimitKey, clubLimit);

        // 初始化社团报名人数
        // 从缓存中获取当前报名人数 
        const currentCount = await cache.get(clubCountKey);
        // 如果缓存中没有当前报名人数，从数据库中获取
        if (currentCount === null) {
            // 从数据库中获取当前报名人数
            const registrationResult = await query('SELECT COUNT(*) as count FROM club_registrations WHERE club_name = ?', [club_name]);
            const dbCount = registrationResult.rows[0].count;
            await cache.set(clubCountKey, dbCount);
        }

        // 执行秒杀Lua脚本
        const result = await cache.eval(seckillScript, 3,
            studentKey, clubCountKey, clubLimitKey, club_name, student_name, timestampToDateTime(Date.now()));


        console.log('result', result);
        // 解析脚本执行结果
        const [success, message] = result;

        if (success === 1) {
            // 秒杀成功，添加到数据库
            await query(
                'INSERT INTO club_registrations (class_name, student_name, club_name, club_location) VALUES (?, ?, ?, ?)',
                [class_name, student_name, club_name, clubLocation]
            );

            // 手动构建返回对象
            const newRegistration = {
                class_name,
                student_name,
                club_name,
                club_location: clubLocation,
                created_at: new Date().toISOString()
            };

            // 获取插入的记录ID
            const idResult = await query('SELECT LAST_INSERT_ID() as id');
            newRegistration.id = idResult.rows[0].id;

            // 清除相关缓存
            await cache.del('club_registrations:all');
            logger.info(`学生 ${student_name} 秒杀报名社团 ${club_name} 成功`);


            return res.status(201).json({
                registration: newRegistration,
                message: '秒杀报名成功'
            });
        } else {
            // 秒杀失败
            logger.info(`学生 ${student_name} 秒杀报名社团 ${club_name} 失败: ${message}`);

            return res.status(400).json({
                message: message
            });
        }
    } catch (error) {
        logger.error(`社团秒杀报名错误: ${error.message}`);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

/**
 * 创建社团报名记录
 */
const createClubRegistration = async (req, res) => {
    try {
        const { class_name, student_name, club_name, club_location, remarks } = req.body;

        // 验证必要字段
        if (!class_name || !student_name || !club_name || !club_location) {
            return res.status(400).json({
                message: '班级名称、学生姓名、社团名称和社团地点为必填项'
            });
        }

        // 插入数据库
        await query(
            'INSERT INTO club_registrations (class_name, student_name, club_name, club_location, remarks) VALUES (?, ?, ?, ?, ?)',
            [class_name, student_name, club_name, club_location, remarks || null]
        );

        // 手动构建返回对象
        const newRegistration = {
            class_name,
            student_name,
            club_name,
            club_location,
            remarks: remarks || null,
            created_at: new Date().toISOString()
        };

        // 获取插入的记录ID
        const idResult = await query('SELECT LAST_INSERT_ID() as id');
        newRegistration.id = idResult.rows[0].id;

        // 清除相关缓存
        await cache.del('club_registrations:all');
        logger.info('创建社团报名记录成功，并清除相关缓存');

        res.status(201).json({
            registration: newRegistration,
            message: '社团报名成功'
        });
    } catch (error) {
        logger.error('创建社团报名记录错误:', error);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

/**
 * 更新社团报名记录
 */
const updateClubRegistration = async (req, res) => {
    try {
        const { id } = req.params;
        const { class_name, student_name, club_name, club_location, remarks } = req.body;

        // 验证ID
        const existingResult = await query('SELECT * FROM club_registrations WHERE id = ?', [id]);
        if (existingResult.rows.length === 0) {
            return res.status(404).json({
                message: '社团报名记录不存在'
            });
        }

        // 验证必要字段
        if (!class_name || !student_name || !club_name || !club_location) {
            return res.status(400).json({
                message: '班级名称、学生姓名、社团名称和社团地点为必填项'
            });
        }

        // 更新数据库
        await query(
            'UPDATE club_registrations SET class_name = ?, student_name = ?, club_name = ?, club_location = ?, remarks = ? WHERE id = ?',
            [class_name, student_name, club_name, club_location, remarks || null, id]
        );

        // 查询更新后的记录
        const result = await query('SELECT * FROM club_registrations WHERE id = ?', [id]);
        const updatedRegistration = result.rows[0];

        // 清除相关缓存
        await cache.del('club_registrations:all');
        await cache.del(`club_registrations:${id}`);
        logger.info(`更新社团报名记录ID: ${id}成功，并清除相关缓存`);

        res.json({
            registration: updatedRegistration,
            message: '社团报名记录更新成功'
        });
    } catch (error) {
        logger.error(`更新社团报名记录ID: ${id}错误: ${error.message}`);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

/**
 * 删除社团报名记录
 */
const deleteClubRegistration = async (req, res) => {
    try {
        const { id } = req.params;

        // 验证ID
        const existingResult = await query('SELECT * FROM club_registrations WHERE id = ?', [id]);
        if (existingResult.rows.length === 0) {
            return res.status(404).json({
                message: '社团报名记录不存在'
            });
        }

        // 删除记录
        await query('DELETE FROM club_registrations WHERE id = ?', [id]);

        // 清除相关缓存
        await cache.del('club_registrations:all');
        await cache.del(`club_registrations:${id}`);
        logger.info(`删除社团报名记录ID: ${id}成功，并清除相关缓存`);

        res.json({
            message: '社团报名记录删除成功'
        });
    } catch (error) {
        logger.error(`删除社团报名记录ID: ${id}错误: ${error.message}`);
        res.status(500).json({
            message: '服务器内部错误'
        });
    }
};

export {
    getClubRegistrations,
    getClubRegistrationById,
    createClubRegistration,
    getClubRegistrationsFromCache,
    updateClubRegistration,
    deleteClubRegistration,
    seckillClubRegistration
};

// 从缓存或数据库中获取秒杀状态：进行中、未开始、已结束
async function getSeckillStatus() {
    try {
        // 从缓存中获取
        const cachedStatus = await cache.get('seckill_status');
        if (cachedStatus) {
            return cachedStatus;
        }
        // 从数据库中获取
        const result = await query('SELECT seckill_status FROM seckill_club_config WHERE id = 1');
        if (result.rows.length === 0) {
            throw new Error('未配置秒杀状态');
        }

        const seckillStatus = result.rows[0].seckill_status;
        // 缓存秒杀状态
        await cache.set('seckill_status', seckillStatus, 60 * 60); // 缓存1小时
        return seckillStatus;
    } catch (error) {
        logger.error('获取秒杀状态错误:', error);
        throw error;
    }
}

// 从缓存或数据库中获取社团信息
async function getClubInfo(clubName) {
    try {
        // 从缓存中获取
        const cachedClub = await cache.get(`club:${clubName}`);
        if (cachedClub) {
            try {
                // 尝试解析缓存值
                const parsedClub = JSON.parse(cachedClub);
                return parsedClub;
            } catch (e) {
                // 解析失败，记录错误并清除无效缓存
                const delResult = await cache.del(`club:${clubName}`);
            }
        }
        // 从数据库中获取
        const result = await query('SELECT * FROM clubs WHERE club_name = ?', [clubName]);
        if (result.rows.length === 0) {
            throw new Error('社团不存在');
        }
        const club = result.rows[0];
        // 缓存社团信息
        const jsonClub = JSON.stringify(club);
        await cache.set(`club:${clubName}`, jsonClub, 60 * 60); // 缓存1小时
        return club;
    } catch (error) {
        throw error;
    }
}


